package com.tygz.controller;

import java.io.File;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;
import com.auto.base.controller.SysAccessoryController;
import com.auto.base.pojo.SysAccessory;
import com.auto.base.pojo.SysUser;
import com.auto.base.service.SysAccessoryService;
import com.auto.util.SystemUtil;
import com.base.common.CommonConstants;
import com.base.common.RequestParameters;
import com.base.util.JUtil;
import com.base.util.ZipTool;
import com.tygz.service.SysAccessoryExtService;

@Controller
@RequestMapping("/sys/SysAccessoryExt")
public class SysAccessoryExtController extends SysAccessoryController {
	
	private final Logger log = LoggerFactory.getLogger(SysAccessoryExtController.class);
	
	@Resource
    public  SysAccessoryExtService service;
	@Resource
    public  SysAccessoryService sysAccessoryService;

	
	@RequestMapping(value = "upload")
	@ResponseBody
	public Object upload(@RequestParam MultipartFile[] uploadFiles,@ModelAttribute SysAccessory  record, HttpServletRequest request) {
		int res = 0;
		try {
			if(null == uploadFiles || uploadFiles.length == 0 ){
				return setFail("上传文件为空!");
			}
			MultipartFile myfile = uploadFiles[0];
			if(myfile.isEmpty()){
				return setFail("文件未上传!");
			}
			if(JUtil.isNULL(record)){
				return setFail("传入对象为空!");
			}
			
			if(JUtil.isNULL(record.getAccessoryClass())){
				return setFail("附件类型为空!");
			}
			
			//设置添加人
			SysUser sysUser = getLoginSysUser(request);
            if(JUtil.isNULL(record.getId())){
            record.setAddUser(sysUser.getId());
            record.setAddTime(new Date().getTime());
            record.setUpdateTime(record.getAddTime());
			}else{
			record.setUpdateTime(new Date().getTime());
			}
			
			String oldFileName = myfile.getOriginalFilename();
			String suffix = JUtil.getFileSuffix(oldFileName);
	        record.setAccessoryOldName(oldFileName);//原始文件名称
	        record.setAccessoryType(suffix);//文件类型
	        String fileName =JUtil.getFileNameByParameters(record.getAccessoryClass(),suffix);
	        record.setAccessoryName((JUtil.isNull(record.getAccessoryName())?"":record.getAccessoryName()).concat(fileName));//文件名称
	        
	        long size =  myfile.getSize();
	        String spilt ="_";
	        String fullSize = JUtil.getFormetFileSize(size,spilt);
	        String[] fileSizeDesc = fullSize.split(spilt);
	        double relSize = Double.parseDouble(fileSizeDesc[0]);//大小
	        String unit = fileSizeDesc[1];//单位
	        record.setAccessoryFileUnit(unit);
	        record.setAccessoryFileSize(BigDecimal.valueOf(relSize));
	        
	        String filePathPreffix = SystemUtil.getInstance().getParamMap().get("sys_file_save_dir");
//	        if(null == filePathPreffix){
//	        	filePathPreffix = request.getSession().getServletContext().getRealPath("/WEB-INF/upload");
//	        }
	        
	        String realPath = filePathPreffix+"/"+record.getAccessoryClass();
	        File file = new File(realPath);
	        if(!file.exists()){//地址不存在处理
	        	file.mkdirs();
	        }
	        if(JUtil.isNULL(record.getId())){
	        	res =  this.service.upload(record, realPath, myfile.getInputStream());
	        }else{
				res = record.getId();
	        }
	        
			log.info("全部上传成功！");
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return setException("上传异常!",e.getMessage());
		}
		String url = SystemUtil.getInstance().getParamMap().get("sys_file_down_url_preffix")+"/"+record.getAccessoryClass()+"/"+record.getAccessoryName();
        JSONObject obj = new JSONObject();
        obj.put("url", url);
        obj.put("picId", res);
		return setSuccess("上传成功!",obj);
	}
	
	@RequestMapping(value = "down")
	@ResponseBody
	public Object down(@ModelAttribute final RequestParameters requestParameters, HttpServletRequest request) {
		try {
			if(JUtil.isNull(requestParameters.getPks())){
				return setException("下载ID为空!");
			}
			SysAccessory record = new SysAccessory();
			record.setEnabled(CommonConstants.ENABLE);
			record.setId(JUtil.strToInt(requestParameters.getPks()));
			record = sysAccessoryService.findSysAccessory(record, null);
			if(JUtil.isNULL(record)){
				return setException("下载的资料为空!");
			}
			   String fileDownUrlPreffix = SystemUtil.getInstance().getParamMap().get("sys_file_down_url_preffix");
		        if(null == fileDownUrlPreffix){
		        	String path = request.getContextPath();
		        	fileDownUrlPreffix  = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path;
		        }
		        
		        String realPath = fileDownUrlPreffix+"/"+record.getAccessoryClass()+"/"+record.getAccessoryName();
			
			return setSuccess("获取成功", realPath);
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return setException("下载异常!",e.getMessage());
		}
	}
	
	
	/**
	 * 附件打包下载哦
	 * @return
	 */
	@RequestMapping(value = "packageAccessory")
	public void packageAccessory(@ModelAttribute SysAccessory  record,HttpServletRequest request,HttpServletResponse response) {
		try {
			String sysFileSaveDir = SystemUtil.getInstance().getParamMap().get("sys_file_save_dir");
			List<File> listFile = new ArrayList<File>();
			if(!JUtil.isNULL(record.getId())){
				SysAccessory newQuery = new SysAccessory();
				newQuery.setEnabled(CommonConstants.ENABLE);
				newQuery.setId(record.getId());
				newQuery  = this.sysAccessoryService.findSysAccessory(newQuery, null);
				if(null!=newQuery){
					String realPath = sysFileSaveDir+"/"+newQuery.getAccessoryClass()+"/"+newQuery.getAccessoryName();
					ZipTool.downZipFiles(response, realPath);
					return;
				}
				
			}
			record.setEnabled(CommonConstants.ENABLE);
			List<SysAccessory> list = this.sysAccessoryService.listSysAccessory(record, null, null, null);
			if(JUtil.isNULL(list) || list.isEmpty()){
				return;
			}
			for(SysAccessory accessory:list){
				setFileByAccessoryInfo(listFile,accessory,sysFileSaveDir);
			}
			ZipTool.downZipFiles(response, listFile);
			return;
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}
	}
	
	private void setFileByAccessoryInfo(List<File> list,SysAccessory  record,String sysFileSaveDir){
		String realPath = sysFileSaveDir+"/"+record.getAccessoryClass()+"/"+record.getAccessoryName();
		File file = new File(realPath);
		if(file.exists()){
			list.add(file);
		}
	}
	

}
